package org.zpmis.api.business;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Service;
import org.zpmis.common.base.AdminLoginUser;
import org.zpmis.common.base.BaseWebService;
import org.zpmis.common.exception.BusinessException;
import org.zpmis.common.result.ResultCode;
import org.zpmis.common.utils.StringUtil;
import org.zpmis.domain.role.model.SysPermission;
import org.zpmis.domain.role.qo.AddSysPermissionQo;
import org.zpmis.domain.role.qo.DelSysPermissionQo;
import org.zpmis.domain.role.qo.EditSysPermissionQo;
import org.zpmis.domain.role.qo.SysPermissionListQo;
import org.zpmis.domain.role.service.SysPermissionService;
import org.zpmis.domain.role.vo.SysPermissionListVo;
import tk.mybatis.mapper.entity.Condition;
import tk.mybatis.mapper.entity.Example;

import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created with CodeGenerator
 * Description:
 * @author  Yang
 * Date: 2021-5-31
 * Time: 14:00:27
 */
@Service
@Slf4j
public class SysPermissionWebService extends BaseWebService {
     @Reference
     private SysPermissionService sysPermissionService;

    /**
     * 新增权限
     * @param addSysPermissionQo
     * @throws BusinessException
     * @throws Exception
     */
    public void addSysPermission(AddSysPermissionQo addSysPermissionQo) throws BusinessException,Exception{
        //获取当前登录用户
        AdminLoginUser adminLoginUser = super.getAdminLoginUser();
        if(adminLoginUser == null){
            throw new BusinessException(ResultCode.USER_NOT_LOGIN);
        }
        sysPermissionService.save(
        SysPermission.builder()
                .apiUrl(addSysPermissionQo.getApiUrl())
                .permissionCode(addSysPermissionQo.getPermissionCode())
                .permissionName(addSysPermissionQo.getPermissionName())
                .createTime(Instant.now().toEpochMilli())
                .createUser(adminLoginUser.getId())
                .isDeleted(false)
                .permissionGroup(addSysPermissionQo.getPermissionGroup())
                .build()
        );
    }

    /**
     * 修改权限
     * @param editSysPermissionQo
     * @throws BusinessException
     * @throws Exception
     */
    public void editSysPermission(EditSysPermissionQo editSysPermissionQo) throws BusinessException,Exception{
        Long id = editSysPermissionQo.getId();
        SysPermission sysPermission = sysPermissionService.findById(id);
        if(sysPermission == null){
            throw new BusinessException(ResultCode.DATA_NOT_FOUND);
        }
        //获取当前登录用户
        AdminLoginUser adminLoginUser = super.getAdminLoginUser();
        if(adminLoginUser == null){
            throw new BusinessException(ResultCode.USER_NOT_LOGIN);
        }
        sysPermission.setApiUrl(editSysPermissionQo.getApiUrl());
        sysPermission.setPermissionCode(editSysPermissionQo.getPermissionCode());
        sysPermission.setPermissionName(editSysPermissionQo.getPermissionName());
        sysPermission.setUpdateTime(Instant.now().toEpochMilli());
        sysPermission.setUpdateUser(adminLoginUser.getId());
        sysPermission.setPermissionGroup(editSysPermissionQo.getPermissionGroup());
        sysPermissionService.update(sysPermission);
    }

    /**
     * 删除权限
     * @param delSysPermissionQo
     * @throws BusinessException
     * @throws Exception
     */
    public void delSysPermission(DelSysPermissionQo delSysPermissionQo) throws BusinessException,Exception{
        Long id = delSysPermissionQo.getId();
        SysPermission sysPermission = sysPermissionService.findById(id);
        if(sysPermission == null){
            throw new BusinessException(ResultCode.DATA_NOT_FOUND);
        }
        //获取当前登录用户
        AdminLoginUser adminLoginUser = super.getAdminLoginUser();
        if(adminLoginUser == null){
            throw new BusinessException(ResultCode.USER_NOT_LOGIN);
        }
        sysPermissionService.update(
        SysPermission.builder()
                .id(id)
                .updateTime(Instant.now().toEpochMilli())
                .updateUser(adminLoginUser.getId())
                .isDeleted(true)
                .build()
        );
    }

    /**
     * 权限列表查询
     * @param sysPermissionListQo
     * @return
     * @throws Exception
     */
    public PageInfo sysPermissionList(SysPermissionListQo sysPermissionListQo) throws Exception{
        String permissionCode = sysPermissionListQo.getPermissionCode();
        String permissionName = sysPermissionListQo.getPermissionName();
        Long startTime = sysPermissionListQo.getStartTime();
        Long endTime = sysPermissionListQo.getEndTime();

        Condition condition = new Condition(SysPermission.class);
        Example.Criteria criteria = condition.createCriteria();
        criteria.andEqualTo("isDeleted",0);

        if(StringUtil.isNotEmpty(permissionCode)){
            criteria.andLike("permissionCode","%"+permissionCode+"%");
        }
        if(StringUtil.isNotEmpty(permissionName)){
            criteria.andLike("permissionName","%"+permissionName+"%");
        }

        if(startTime != null && endTime != null){
            criteria.andGreaterThanOrEqualTo("createTime",startTime);
            criteria.andLessThanOrEqualTo("createTime",endTime);
        }

        if(startTime != null && endTime == null){
            criteria.andGreaterThanOrEqualTo("createTime",startTime);
            criteria.andLessThanOrEqualTo("createTime",Instant.now().toEpochMilli());
        }

        if(startTime == null && endTime != null){
            criteria.andLessThanOrEqualTo("createTime",endTime);
        }
        condition.orderBy("createTime").desc();
        PageHelper.startPage(sysPermissionListQo.getPageNum(),sysPermissionListQo.getPageSize());
        List<SysPermission> sysPermissionList = sysPermissionService.findByCondition(condition);
        PageInfo pageInfo = new PageInfo<>(sysPermissionList);
        //自定义返回实体
        List<SysPermissionListVo> resultList = sysPermissionList.stream().map(SysPermissionListVo::new).collect(Collectors.toList());
        pageInfo.setList(resultList);
        return pageInfo;
    }

    /**
     * 获取系统所有权限
     * @return
     */
    public Map<String, List<SysPermissionListVo>> allSysPermission() {
        Condition condition = new Condition(SysPermission.class);
        Example.Criteria criteria = condition.createCriteria();
        criteria.andEqualTo("isDeleted",0);
        List<SysPermission> sysPermissionList = sysPermissionService.findByCondition(condition);
        //自定义返回实体
        List<SysPermissionListVo> resultList = sysPermissionList.stream().map(SysPermissionListVo::new).collect(Collectors.toList());
        Map<String, List<SysPermissionListVo>> listMap = resultList.stream().collect(Collectors.groupingBy(result -> result.getPermissionGroup()));
        return listMap;
    }
}
